﻿using System.IO;
using System.Net.Sockets;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace Choucius.Boilerplate9.RfidData
{
    /// <summary>
    /// UR5002 / UR6258
    /// </summary>
    public class RfidDataAppService : IRfidDataAppService
    {
        /// <summary>
        /// 获取RFID数据
        /// </summary>
        /// <returns></returns>
        public async Task<string> GetRfidDataAsync()
        {
            // 假设RFID数据是通过TCP连接以ASCII编码发送的
            string host = "192.168.1.190"; // RFID读写器的IP地址
            int port = 6000; // RFID读写器监听的端口
            var ipEndPoint = new IPEndPoint(IPAddress.Parse(host), port);

            using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
            {
                socket.Connect(ipEndPoint);
                using (var ns = new NetworkStream(socket))
                using (var reader = new StreamReader(ns))
                {
                    // 发送命令到RFID读写器，获取数据
                    socket.Send(Encoding.ASCII.GetBytes("GET_DATA\n"));
                    // 读取响应
                    char[] buffer = new char[1024];
                    int bytesRead = reader.Read(buffer, 0, buffer.Length);
                    string response = new string(buffer, 0, bytesRead);
                    // 处理响应并返回
                    return response;
                }
            }
        }

        /// <summary>
        /// 写入RFID数据
        /// </summary>
        /// <param name="dataToWrite"></param>
        public void WriteDataToRfid(string dataToWrite)
        {
            string rfidReaderIp = "192.168.1.190"; // RFID读写器的IP地址
            int rfidReaderPort = 6000; // RFID读写器的端口号

            using (TcpClient client = new TcpClient())
            {
                client.Connect(rfidReaderIp, rfidReaderPort);
                NetworkStream stream = client.GetStream();

                byte[] data = Encoding.ASCII.GetBytes(dataToWrite);
                stream.Write(data, 0, data.Length);

                // 如果需要读取读写器的响应，可以从stream中读取
                // stream.Read(buffer, 0, buffer.Length);

                client.Close();
            }
        }
    }
}
